import sys
import time

def clipboard_copy(text):
    win32clipboard.OpenClipboard()
    win32clipboard.EmptyClipboard()
    win32clipboard.SetClipboardText(text)
    win32clipboard.CloseClipboard()

def countdown(seconds):
    TEXT = "          Wiping in XXX seconds"
    for i in range(seconds, 0, -1):
        sys.stdout.write(TEXT.replace("XXX", "%03d" % i))
        time.sleep(1)
        sys.stdout.write("\b" * len(TEXT))

def _outputPassword(text, copy, wipe_timeout):
    if copy:
        clipboard_copy(text)
    else:
        sys.stdout.write(text)
        sys.stdout.flush()
    countdown(wipe_timeout)
    if copy:
        clipboard_copy("")
    else:
        sys.stdout.write("\b" * len(text))
        sys.stdout.write("*" * len(text))
        sys.stdout.flush()

try:
    import win32clipboard
    outputPassword = _outputPassword
    
except ImportError:
    print "!!! win32clipboard not available. passwords will be displayed rather than copied"
    def outputPassword(text, copy, wipe_timeout):
        _outputPassword(text, False, wipe_timeout)
